package com.leyou.auth.config;


import com.leyou.auth.utils.RsaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

//@Component
@ConfigurationProperties(prefix = "leyou.jwt")
public class JwtProperties {
    private String secret;  //密钥
    private String pubKeyPath; //公钥路径
    private String priKeyPath;//私钥路径
    private int expire; //过期时间
    private String cookieName;

    public String getCookieName() {
        return cookieName;
    }

    public void setCookieName(String cookieName) {
        this.cookieName = cookieName;
    }

    private PublicKey publicKey;//公钥对象
    private PrivateKey privateKey;//私钥对象
    private final Logger log = LoggerFactory.getLogger(JwtProperties.class);

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * PostConstruct注解表示构造方法执行之后执行，spring调用默认构造初始化对象后执行
     *
     * @return
     */
    @PostConstruct
    public void init() {
        try{
            File pubKey = new File(pubKeyPath);
            File priKey = new File((priKeyPath));
            if (!pubKey.exists()||!priKey.exists()){
                RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
            }
            this.publicKey=RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey=RsaUtils.getPrivateKey(priKeyPath);
        }catch (Exception e){
            log.error("初始化公钥私钥失败",e);
            throw new RuntimeException();
        }
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getPubKeyPath() {
        return pubKeyPath;
    }

    public void setPubKeyPath(String pubKeyPath) {
        this.pubKeyPath = pubKeyPath;
    }

    public String getPriKeyPath() {
        return priKeyPath;
    }

    public void setPriKeyPath(String priKeyPath) {
        this.priKeyPath = priKeyPath;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }
}
